import { Document, Schema, Model, connect, connection, model } from 'mongoose';
import { v4 as uuidv4 } from 'uuid';
import log from './log';

export interface User extends Document {
  _id: string;
  /** 用户名 */
  username: string;
  /** 密码 */
  password: string;
  /** 错误剩余次数 */
  number: number;
}

const userSchema = new Schema({
  _id: { type: String, default: uuidv4 },
  username: String,
  password: String,
  number: Number,
}, { versionKey: false });

(async ({ username, password, host, port, dbName, authDbName }) => {
  let reconnect = false;
  username = encodeURIComponent(username);
  password = encodeURIComponent(password);
  dbName = encodeURIComponent(dbName);
  authDbName = encodeURIComponent(authDbName);
  let mongoClient = await connect(`mongodb://${username}:${password}@${host}:${port}/${dbName}?authSource=${authDbName}`, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  log.app.info('数据库连接成功!');
  connection.on('disconnected', async () => {
    if (!reconnect) {
      log.app.info('数据库尝试重连......');
      setTimeout(async () => {
        mongoClient = await connect(`mongodb://${username}:${password}@${host}:${port}/${dbName}?authSource=${authDbName}`, {
          useNewUrlParser: true,
          useUnifiedTopology: true,
        });
        log.app.info('数据库尝试重连成功!');
        reconnect = false;
      }, 1000);
    }
  });
})(require('../../dbConfig.json'));

export const userModel: Model<User> = model('user', userSchema, 'user');
